/**
 * 文件名：****.java
 * 版权：Copyright Lightkit All Rights Reserved.
 * 描述：*****
 */
package com.lightkits.wms.domain.saleticket.impl;

import com.lightkits.common.db.entity.WmSaleTicketLine;
import com.lightkits.common.db.entity.WmSalesTicket;
import com.lightkits.framework.common.logging.Logger;
import com.lightkits.framework.common.logging.LoggerFactory;
import com.lightkits.framework.common.utility.object.ObjectUtil;
import com.lightkits.framework.common.utility.object.ParseUtil;
import com.lightkits.wms.client.DocumentServiceClient;
import com.lightkits.wms.domain.deliveryorder.service.CreateDeliveryOrderDomain;
import com.lightkits.wms.domain.saleticket.CreateSaleParamsService;
import com.lightkits.wms.domain.saleticket.model.SaleConstrant;
import com.lightkits.wms.dto.document.GenerateDocNumRequestType;
import com.lightkits.wms.dto.document.GenerateDocNumResponseType;
import com.lightkits.wms.dto.saleticket.model.SaleTicketHeadDto;
import com.lightkits.wms.dto.saleticket.model.SaleTicketLineDto;
import com.lightkits.wms.dto.saleticket.model.UpSaleTicketHeadDto;
import com.lightkits.wms.dto.saleticket.model.UpSaleTicketLineDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 售货单参数创建
 *
 * @author jing.wei@hand-china.com
 * @date 2019/5/31 6:01
 **/
@Service
public class CreateSaleParamsServiceImpl implements CreateSaleParamsService {

    private static final Logger LOGGER = LoggerFactory.getLogger(CreateSaleParamsServiceImpl.class);

    private final CreateDeliveryOrderDomain createDeliveryOrderDomain;

    @Autowired
    public CreateSaleParamsServiceImpl(CreateDeliveryOrderDomain createDeliveryOrderDomain) {
        this.createDeliveryOrderDomain = createDeliveryOrderDomain;
    }

    @Autowired
    private DocumentServiceClient client;

    /**
     * 售货单头的创建
     *
     * @param headDto 售货单头
     * @return WmSalesTicket
     **/
    @Override
    public WmSalesTicket createSaleHead(SaleTicketHeadDto headDto) {
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
        WmSalesTicket salesTicket = new WmSalesTicket();
        GenerateDocNumRequestType request = new GenerateDocNumRequestType();
        request.setCount(1);
        request.setSize(SaleConstrant.SIZE);
        request.setType(SaleConstrant.SALE_NUMBER);
        request.setField1(df.format(new Date()));
        GenerateDocNumResponseType response = client.generateDocNumber(request);
        salesTicket.setSalesTickeetNum(response.getDocNumList().get(0));
        salesTicket.setOrganizationId(ParseUtil.tryLongWithException(headDto.getOrgId()));
        if (!ObjectUtil.isNullOrEmpty(headDto.getWorkerId())) {
            salesTicket.setWorkerId(ParseUtil.tryLongWithException(headDto.getWorkerId()));
        }
        if (!ObjectUtil.isNullOrEmpty(headDto.getPriceTotal())) {
            salesTicket.setPriceTotal(new BigDecimal(headDto.getPriceTotal()));
        }
        if (!ObjectUtil.isNullOrEmpty(headDto.getFreight())) {
            salesTicket.setFreight(new BigDecimal(headDto.getFreight()));
        }
        salesTicket.setCurrency(headDto.getCurrency());
        salesTicket.setDeliverWays(headDto.getDelieveyWays());
        salesTicket.setGoodsTotal(new BigDecimal(headDto.getGoodTotal()));
        salesTicket.setInvoice(headDto.getInvoice());
        salesTicket.setCustomerAddress(headDto.getCustomerAddress());
        salesTicket.setCustomerName(headDto.getCustomerName());
        salesTicket.setDeliverAddress(headDto.getCustomerAddress());
        salesTicket.setCustomerPhone(headDto.getCustomerPhone());

        return salesTicket;
    }


    /**
     * 售货单头的创建
     *
     * @param headDto 售货单头
     * @return WmSalesTicket
     **/
    @Override
    public WmSalesTicket createSaleHead(UpSaleTicketHeadDto headDto) {
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
        WmSalesTicket salesTicket = new WmSalesTicket();

        try {
            if (!ObjectUtil.isNullOrEmpty(headDto.getSaleTicketId())) {
                salesTicket = new WmSalesTicket().selectById(headDto.getSaleTicketId());
            } else {
                GenerateDocNumRequestType request = new GenerateDocNumRequestType();
                request.setCount(1);
                request.setSize(SaleConstrant.SIZE);
                request.setType(SaleConstrant.SALE_NUMBER);
                request.setField1(df.format(new Date()));
                GenerateDocNumResponseType response = client.generateDocNumber(request);
                salesTicket.setSalesTickeetNum(response.getDocNumList().get(0));
            }

            salesTicket.setOrganizationId(ParseUtil.tryLongWithException(headDto.getOrgId()));
            if (!ObjectUtil.isNullOrEmpty(headDto.getWorkerId())) {
                salesTicket.setWorkerId(ParseUtil.tryLongWithException(headDto.getWorkerId()));
            }
            if (!ObjectUtil.isNullOrEmpty(headDto.getPriceTotal())) {
                salesTicket.setPriceTotal(new BigDecimal(headDto.getPriceTotal()));
            }
            if (!ObjectUtil.isNullOrEmpty(headDto.getFreight())) {
                salesTicket.setFreight(new BigDecimal(headDto.getFreight()));
            }
            salesTicket.setCurrency(headDto.getCurrency());
            salesTicket.setDeliverWays(headDto.getDelieveyWays());
            salesTicket.setGoodsTotal(new BigDecimal(headDto.getGoodTotal()));
            salesTicket.setInvoice(headDto.getInvoice());
            salesTicket.setBookedMoney(new BigDecimal(headDto.getBookMoney()));
            salesTicket.setCustomerAddress(headDto.getCustomerAddress());
            salesTicket.setCustomerName(headDto.getCustomerName());
            salesTicket.setDeliverAddress(headDto.getCustomerAddress());
            salesTicket.setCustomerPhone(headDto.getCustomerPhone());
            salesTicket.setSoStatus(headDto.getSoStatus());

        } catch (Exception e) {
            LOGGER.error("createSaleHead.error", e);
        }
        return salesTicket;
    }

    /**
     * 创建售货单行
     *
     * @param lineDtos 售货单行参数
     * @param headId   售货单头ID
     * @param currency 货币
     * @return WmSaleTicketLine
     **/
    @Override
    public List<WmSaleTicketLine> createSaleLine(List<SaleTicketLineDto> lineDtos,
                                                 Long headId, String currency) {
        List<WmSaleTicketLine> lines = new ArrayList<>();
        try {
            lineDtos.forEach(line -> {
                WmSaleTicketLine saleTicketLine = new WmSaleTicketLine();
                saleTicketLine.setCurrency(currency);
                saleTicketLine.setItemId(ParseUtil.tryLongWithException(line.getItemId()));
                saleTicketLine.setSalesTicketId(headId);
                saleTicketLine.setTotalPrice(new BigDecimal(line.getTotalPrice()));
                saleTicketLine.setTagId(ParseUtil.tryLongWithException(line.getTagId()));
                if (!ObjectUtil.isNullOrEmpty(line.getMarketPrice())) {
                    saleTicketLine.setMarketPrice(new BigDecimal(line.getMarketPrice()));
                }
                lines.add(saleTicketLine);
            });
        } catch (Exception e) {
            LOGGER.error("createSaleLine.error", e);
        }
        return lines;
    }

    /**
     * 创建售货单行
     *
     * @param upLineDtos 售货单行参数
     * @param headId     售货单头ID
     * @param currency   货币
     * @return WmSaleTicketLine
     **/
    @Override
    public List<WmSaleTicketLine> createSaleLines(List<UpSaleTicketLineDto> upLineDtos,
                                                  Long headId, String currency) {
        List<WmSaleTicketLine> lines = new ArrayList<>();

        try {
            upLineDtos.forEach(line -> {
                WmSaleTicketLine saleTicketLine = new WmSaleTicketLine();
                saleTicketLine.setCurrency(currency);
                saleTicketLine.setSalesTicketId(headId);
                saleTicketLine.setItemId(ParseUtil.tryLongWithException(line.getItemId()));
                saleTicketLine.setTagId(ParseUtil.tryLongWithException(line.getTagId()));
                lines.add(saleTicketLine);
            });
        } catch (Exception e) {
            LOGGER.error("createSaleLine.error", e);
        }
        return lines;
    }

}
